// 移动端APP扫码登录示例
// 使用 React Native 或 Flutter

// React Native 示例
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import { Camera } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';
import AsyncStorage from '@react-native-async-storage/async-storage';

const QRCodeScanner = () => {
    const [hasPermission, setHasPermission] = useState(null);
    const [scanned, setScanned] = useState(false);

    // 请求相机权限
    useEffect(() => {
        (async () => {
            const { status } = await Camera.requestCameraPermissionsAsync();
            setHasPermission(status === 'granted');
        })();
    }, []);

    // 处理扫码结果
    const handleBarCodeScanned = async ({ data }) => {
        setScanned(true);
        
        try {
            // 解析二维码内容
            const url = new URL(data);
            const qrCodeId = url.searchParams.get('code');
            const timestamp = url.searchParams.get('t');
            
            if (!qrCodeId) {
                Alert.alert('错误', '无效的二维码');
                return;
            }
            
            // 检查二维码是否过期
            const currentTime = Date.now();
            const qrTime = parseInt(timestamp);
            
            if (currentTime - qrTime > 300000) { // 5分钟过期
                Alert.alert('错误', '二维码已过期');
                return;
            }
            
            // 显示确认对话框
            Alert.alert(
                '确认登录',
                '是否确认在PC端登录？',
                [
                    {
                        text: '取消',
                        style: 'cancel',
                        onPress: () => setScanned(false)
                    },
                    {
                        text: '确认',
                        onPress: () => confirmLogin(qrCodeId)
                    }
                ]
            );
            
        } catch (error) {
            Alert.alert('错误', '二维码格式错误');
            setScanned(false);
        }
    };

    // 确认登录
    const confirmLogin = async (qrCodeId) => {
        try {
            // 获取当前用户的token
            const userToken = await AsyncStorage.getItem('userToken');
            
            if (!userToken) {
                Alert.alert('错误', '请先登录移动端APP');
                setScanned(false);
                return;
            }
            
            // 发送确认登录请求
            const response = await fetch('https://yourapp.com/api/qrcode/confirm', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${userToken}`
                },
                body: JSON.stringify({
                    qrCodeId: qrCodeId,
                    userId: getCurrentUserId(), // 获取当前用户ID
                    token: userToken
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                Alert.alert('成功', 'PC端登录成功！');
                // 可以跳转到成功页面
            } else {
                Alert.alert('错误', result.message || '确认登录失败');
            }
            
        } catch (error) {
            console.error('确认登录失败:', error);
            Alert.alert('错误', '网络错误，请重试');
        }
        
        setScanned(false);
    };

    if (hasPermission === null) {
        return <View><Text>请求相机权限...</Text></View>;
    }
    
    if (hasPermission === false) {
        return <View><Text>没有相机权限</Text></View>;
    }

    return (
        <View style={{ flex: 1 }}>
            <BarCodeScanner
                onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                style={{ flex: 1 }}
            />
            
            {scanned && (
                <TouchableOpacity 
                    style={{
                        position: 'absolute',
                        bottom: 50,
                        left: 50,
                        right: 50,
                        backgroundColor: '#007AFF',
                        padding: 15,
                        borderRadius: 10,
                        alignItems: 'center'
                    }}
                    onPress={() => setScanned(false)}
                >
                    <Text style={{ color: 'white', fontSize: 16 }}>
                        重新扫描
                    </Text>
                </TouchableOpacity>
            )}
        </View>
    );
};

export default QRCodeScanner;

// Flutter 示例
/*
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class QRCodeScannerPage extends StatefulWidget {
  @override
  _QRCodeScannerPageState createState() => _QRCodeScannerPageState();
}

class _QRCodeScannerPageState extends State<QRCodeScannerPage> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  QRViewController? controller;
  bool scanned = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: QRView(
        key: qrKey,
        onQRViewCreated: _onQRViewCreated,
      ),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      if (!scanned) {
        scanned = true;
        _handleQRCode(scanData.code!);
      }
    });
  }

  void _handleQRCode(String data) async {
    try {
      // 解析二维码内容
      Uri uri = Uri.parse(data);
      String? qrCodeId = uri.queryParameters['code'];
      String? timestamp = uri.queryParameters['t'];
      
      if (qrCodeId == null) {
        _showError('无效的二维码');
        return;
      }
      
      // 检查是否过期
      int currentTime = DateTime.now().millisecondsSinceEpoch;
      int qrTime = int.parse(timestamp!);
      
      if (currentTime - qrTime > 300000) {
        _showError('二维码已过期');
        return;
      }
      
      // 显示确认对话框
      bool? confirmed = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('确认登录'),
          content: Text('是否确认在PC端登录？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context, true),
              child: Text('确认'),
            ),
          ],
        ),
      );
      
      if (confirmed == true) {
        await _confirmLogin(qrCodeId);
      }
      
    } catch (e) {
      _showError('二维码格式错误');
    }
    
    scanned = false;
  }

  Future<void> _confirmLogin(String qrCodeId) async {
    try {
      // 获取用户token
      String? userToken = await _getUserToken();
      
      if (userToken == null) {
        _showError('请先登录移动端APP');
        return;
      }
      
      // 发送确认请求
      final response = await http.post(
        Uri.parse('https://yourapp.com/api/qrcode/confirm'),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $userToken',
        },
        body: jsonEncode({
          'qrCodeId': qrCodeId,
          'userId': await _getCurrentUserId(),
          'token': userToken,
        }),
      );
      
      final result = jsonDecode(response.body);
      
      if (result['success']) {
        _showSuccess('PC端登录成功！');
      } else {
        _showError(result['message'] ?? '确认登录失败');
      }
      
    } catch (e) {
      _showError('网络错误，请重试');
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }

  void _showSuccess(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.green),
    );
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
*/
